// pages/news-comment/news-comment.js
import formatTime from '../../utils/formatTime.js'
const app = getApp()
let newsId = ""
Page({
  data: {
    news: {},
    commentList: [],
    newsId: '',
    allAd:null
  },
  onLoad(e) {
    this.setData({
      newsId: e.newsid,
      allAd:app.globalData.ads.allAd
    })
    // 查询加载文章详情及评论
    this._getNewsDetail()
  },
  // 进入店铺
  enterShop(e){
// 根据openid去数据库拿店铺信息
let openid2 = e.currentTarget.dataset.openid
// 跳转到店铺详情页面
wx.navigateTo({
  url: '/pages/my-shop/my-shop?openid2='+ openid2,
})
  },
  // 查询福利详情页
  selectYouhui() {
    let news = null
    let commentList = null
    wx.cloud.callFunction({
      name: 'youhui',
      data: {
        tag: 'user',
        id: this.data.newsId,
      }
    }).then(res => {
      news = res.result
      // 查询评论数据
      wx.cloud.callFunction({
        name: 'youhui',
        data: {
          tag: 'pinglun',
          newsId: this.data.newsId,
        }
      }).then(res => {
        // 格式化时间
        commentList = res.result
        for (let i = 0, len = commentList.length; i < len; i++) {
          commentList[i].createTime = formatTime(new Date(commentList[i].createTime))
        }
        this.setData({
          commentList,
          news
        })

        wx.hideLoading()
      })
    })

  },
  // 查询加载文章详情及评论
  _getNewsDetail() {
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: 'news',
      data: {
        newsId: this.data.newsId,
        $url: 'detail',
      }
    }).then(res => {
      if (res.result.detail.length == 0) {
        // 查询福利详情页数据
        this.selectYouhui();
        return
      }
      // 格式化时间
      let commentList = res.result.commentList
      for (let i = 0, len = commentList.length; i < len; i++) {
        commentList[i].createTime = formatTime(new Date(commentList[i].createTime))
      }
      this.setData({
        commentList,
        news: res.result.detail[0],
      })
      wx.hideLoading()
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    const news = this.data.news
    return {
      title: news.content,
      path: `/pages/news-comment/news-comment?newsid=${news._id}`,
    }
  },
  // 分享到朋友圈
  onShareTimeline: function (res) {
    // var query = {
    //   data: goods_id
    // };
    // query = JSON.stringify(query.data);  
    return {
      title: '曲靖商家送福利，每天都有福利领，领到你手软',
      query: query,
      imageUrl: '/images/fuli.png',
    }
  }
})